﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using NLog;

namespace Labthink.PCSoft.UniversalHost4.UserControls
{
    public partial class Main
    {
        private Logger _logger = LogManager.GetCurrentClassLogger();
        private NotifyManager _notify;

        public Main()
        {
            InitializeComponent();
            var updateTimeTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(50) };
            updateTimeTimer.Tick += UpdateTimeTimer_Tick;
            if (Common.UiSetting.ShowTime)
            {
                updateTimeTimer.IsEnabled = true;
            }
            else
            {
                updateTimeTimer.IsEnabled = false;
                LblTime.Visibility = Visibility.Collapsed;
            }

            if (!Common.UiSetting.ShowReceivedByteCount)
            {
                ReceivedByteCount.Visibility = Visibility.Collapsed;
            }
            else
            {
                SerialPortHelper.OnReceivedByteCountChangedHandler += OnReceivedByteCountChangedHandler;
            }

            if (!Common.UiSetting.ShowSentByteCount)
            {
                SendByteCount.Visibility = Visibility.Collapsed;
            }
            else
            {
                SerialPortHelper.OnSentByteCountChangedHandler += OnSentByteCountChangedHandler;
            }
        }

        private void OnSentByteCountChangedHandler(object sender, Instrument.Model.ComByteCountEventArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                LblSentByteCount.Content = e.SentCount.ToString();
            });
        }

        private void OnReceivedByteCountChangedHandler(object sender, Instrument.Model.ComByteCountEventArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                LblReceivedCount.Content = e.ReceivedCount.ToString();
            });
        }

        private void UpdateTimeTimer_Tick(object sender, EventArgs e)
        {
            string format = Common.UiSetting.TimeFormat;
            LblTime.Content = DateTime.Now.ToString(format);
        }

        private void Main_OnLoaded(object sender, RoutedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }

            _notify = NotifyManager.InstanceManager(Application.Current.MainWindow);
            _logger.Debug("Main_OnLoaded");
        }

        private void Main_OnUnloaded(object sender, RoutedEventArgs e)
        {

        }

        private void _triggerButtonsStatus(bool status)
        {
            TabControl.IsEnabled = status;
            Loading.Visibility = status ? Visibility.Collapsed : Visibility.Visible;
        }

        public T FindFirstVisualChild<T>(DependencyObject obj, string childName) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child is T dependencyObject && dependencyObject.GetValue(NameProperty).ToString() == childName)
                {
                    return dependencyObject;
                }

                T childOfChild = FindFirstVisualChild<T>(child, childName);
                if (childOfChild != null)
                {
                    return childOfChild;
                }
            }
            return null;
        }

        private void TabControl_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //Dashboard.ClosePopup();
        }

        private void Main_OnTouchLeave(object sender, TouchEventArgs e)
        {
            //Dashboard.ClosePopup();
        }

        private void Main_OnMouseLeave(object sender, MouseEventArgs e)
        {
            //Dashboard.ClosePopup();
        }

        //private async void TxtDeviceReset_Click(object sender, RoutedEventArgs e)
        //{
        //    if (!Common.Instrument.IsControl)
        //    {
        //        MessageBox.Show(Resources.GetLanguageValue("NoControl"));
        //        return;
        //    }
        //    if (MessageBox.Show(Resources.GetLanguageValue("ResetAlert"), "", MessageBoxButton.OKCancel,
        //            MessageBoxImage.Asterisk, MessageBoxResult.OK) == MessageBoxResult.OK)
        //    {
        //        var sd = await Common.Instrument.Commands.DeviceResetAsync();
        //        if (sd.ErrorCode == 0)
        //        {
        //            OnLogout?.Invoke(this, EventArgs.Empty);
        //            return;
        //        }
        //        MessageBox.Show(sd.ErrorMsg);
        //    }
        //}

        private void Main_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

        }
    }
}

